<?php

/**
 * Paypal Class
 *
 * Integrate the Paypal payment gateway in your site using this easy
 * to use library. Just see the example code to know how you should
 * proceed. Btw, this library does not support the recurring payment
 * system. If you need that, drop me a note and I will send to you.
 *
 * @package		Payment Gateway
 * @category	Library
 * @author      Md Emran Hasan <phpfour@gmail.com>
 * @link        http://www.phpfour.com
 */

include_once ('PaymentGateway.php');
include_once ('xml2array.php');
class Google extends PaymentGateway
{

	public $merchant_id;

	public $merchant_key;
    /**
	 * Initialize the Paypal gateway
	 *
	 * @param none
	 * @return void
	 */
	public function __construct()
	{
        parent::__construct();

        // Some default values of the class
		$this->gatewayUrl = 'https://checkout.google.com';
		$this->ipnLogFile = 'google.ipn_results.log';
	}

    /**
     * Enables the test mode
     *
     * @param none
     * @return none
     */
    public function enableTestMode()
    {
        $this->testMode = TRUE;
        $this->gatewayUrl = 'https://sandbox.google.com/checkout';
    }

    /**
     * Set login and secret key
     *
     * @param string user login
     * @param string secret key
     * @return void
     */
    public function setUserInfo($merchant_id,$merchant_key='')
    {
        $this->merchant_id  = $merchant_id;
	$this->merchant_id = $merchant_id;
    }

    public function buildForm()
    {
	$r = "<form method=\"POST\" name=\"gateway_form\" ";
	$r .= "action=\"" . $this->gatewayUrl . "/api/checkout/v2/checkoutForm/".$this->merchant_id."\" accept-charset=\"utf-8\"> \n";

	foreach ($this->fields as $name => $value)
	{
	     $r .= "<input type=\"hidden\" name=\"$name\" value=\"$value\"/>\n";
	}

	$r .= "<input type=\"hidden\" name=\"_charset_\"/>\n";
	$r .= "<p style=\"text-align:center;\"><br/><br/>If you are not automatically redirected to ";
	$r .= "payment website within 5 seconds...<br/><br/>\n";
	$r .= "<input name=\"Google Checkout\" type=\"submit\" value=\"Click Here\"></p>\n";

	$r .= "</form>\n";

	return $r;
    }

    /**
	 * Validate the IPN notification
	 *
	 * @param none
	 * @return boolean
	 */
	public function validateIpn()
	{

		if ($_SERVER['PHP_AUTH_USER'] != $this->merchant_id || $_SERVER['PHP_AUTH_PW'] != $this->merchant_key) {
			return false;
		}
		$this->ipnResponse = $HTTP_RAW_POST_DATA;
		$this->ipnData = xml2array($HTTP_RAW_POST_DATA);
		if (eregi("CHARGED", $this->ipnData['order-state-change-notification']['new-financial-order-state']['value']))
		{
		 	// Valid IPN transaction.
		 	$this->logResults(true);
		 	return true;
		}
		else
		{
		 	// Invalid IPN transaction.  Check the log for details.
			$this->lastError = "IPN Validation Failed .";
			$this->logResults(false);
			return false;
		}
	}
}
